'use strict';

angular.module('afasApp')
  .controller('SigninCtrl', ['$scope', '$state', 'principal', 'Services', 'ServicesLS', function($scope, $state, principal, Services, ServicesLS) {
      $scope.login = {};
      $scope.loginError = false;

      var key = ServicesLS.get('_auth');
      // console.log(key);
      if (typeof key !== 'undefined' && key !== null) {
        // console.log(key);
        $state.go('home');
      };
      $scope.login = function() {

        $scope.loginError = false;
        // here, we fake authenticating and give a fake user

        Services.add('session/'+$scope.login.Email+'/'+$scope.login.Password)
        .then(function(results){
          // console.log(results.data.RoleProfile);
          var roles = [];
          angular.forEach(results.data.RoleProfile.Roles, function(value, key){
            roles.push(value.Action+value.Controller);
          });
          ServicesLS.create('_auth', results.data.key);
          ServicesLS.create('_name', $scope.login.Email);
          ServicesLS.create('_roles', JSON.stringify(roles));

          principal.authenticate({
            name: $scope.login.Email,
            roles: roles
          });

          // console.log($scope.returnToState);

          if ($scope.returnToState) {
            $state.transitionTo($scope.returnToState.name, $scope.returnToStateParams, {
              reload: true,
              inherit: false,
              notify: true
            });
            location.reload();
          } else {
            $state.go('home');
            location.reload();
          };
        }, function(results){
          if (results.status === 401) {
            $scope.loginError = true;
          };
        });


      };
    }
  ]);